package pub.wkq.api.controller.intercept;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import pub.wkq.common.base.BaseInfoProperties;
import pub.wkq.common.utils.SerializationUtils;
import pub.wkq.pojo.Admin;
import pub.wkq.pojo.Users;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <h1>jwt 拦截器</h1>
 *
 * @author: 王开琦
 * @date: 2023/6/5 21:01
 */
@Slf4j
public class JWTCurrentUserInterceptor extends BaseInfoProperties implements HandlerInterceptor {
    /**
     * ThreadLocal 本质上是一个 Map
     */
    public static ThreadLocal<Users> currentUser = new ThreadLocal<>();
    public static ThreadLocal<Admin> adminUser = new ThreadLocal<>();

    /**
     * <h2>在请求之前进行拦截</h2>
     *
     * @param request  请求
     * @param response 响应
     * @param handler  处理器
     * @return 是否拦截
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //使用 ThreadLocal可以再同一个线程内共享数据
        //比如：在拦截器中获取到用户信息，然后在controller中也可以获取到用户信息 ，Interceptor --> 控制器Controller --> 业务层Service --> 数据层Mapper(dao)
        String appUserJson = request.getHeader(APP_USER_JSON);
        String sassUserJson = request.getHeader(SAAS_USER_JSON);
        String adminUserJson = request.getHeader(ADMIN_USER_JSON);
        if (StringUtils.isNotBlank(appUserJson) || StringUtils.isNotBlank(sassUserJson)) {
            String userJson = StringUtils.isNotBlank(appUserJson) ? appUserJson : sassUserJson;
            log.info("userJson:{}", userJson);
            Users users = SerializationUtils.deserializeObject(userJson , Users.class);
            currentUser.set(users);
        }
        if (StringUtils.isNotBlank(adminUserJson)) {
            Admin admin = SerializationUtils.deserializeObject(adminUserJson, Admin.class);
            adminUser.set(admin);
        }
        return true;
    }

    /**
     * <h2>请求之后进行拦截</h2>
     *
     * @param request  请求
     * @param response 响应
     * @param handler  处理器
     * @param ex       异常
     * @throws Exception 异常
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        currentUser.remove();
        adminUser.remove();
    }
}
